package cn.com.frame.core.exception;


import cn.com.frame.commom.web.BaseController;
import cn.com.frame.commom.web.RespData;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.xml.bind.ValidationException;
import java.util.Set;

/**
 * 异常处理类
 */
@ControllerAdvice
@ResponseBody
public class CommonExceptionAdvice extends BaseController {
    private static final Logger logger = LogManager.getLogger(CommonExceptionAdvice.class);

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public RespData handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        logger.error("缺少请求参数", e);
        //return new RespData(HttpStatus.BAD_REQUEST.value(),"缺少请求参数:"+e.getMessage());
        return reFail("缺少请求参数:"+e.getMessage());
    }
    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public RespData handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        logger.error("参数解析失败", e);
        //return new RespData(HttpStatus.BAD_REQUEST.value(),"参数解析失败:"+e.getMessage());
        return reFail("参数解析失败:"+e.getMessage());
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public RespData handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        logger.error("参数验证失败", e);
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String field = error.getField();
        String code = error.getDefaultMessage();
        String message = String.format("%s:%s", field, code);
        //return new RespData(HttpStatus.BAD_REQUEST.value(),"参数验证失败:"+message);
        return reFail("参数验证失败:"+message);
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BindException.class)
    public RespData handleBindException(BindException e) {
        logger.error("参数绑定失败", e);
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String field = error.getField();
        String code = error.getDefaultMessage();
        String message = String.format("%s:%s", field, code);
        //return new RespData(HttpStatus.BAD_REQUEST.value(),"参数绑定失败:"+message);
        return reFail("参数绑定失败:"+message);
    }


    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ConstraintViolationException.class)
    public RespData handleServiceException(ConstraintViolationException e) {
        logger.error("参数验证失败", e);
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        ConstraintViolation<?> violation = violations.iterator().next();
        String message = violation.getMessage();
        //return new RespData(HttpStatus.BAD_REQUEST.value(),"参数验证失败:"+message);
        return reFail("参数验证失败:"+message);
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ValidationException.class)
    public RespData handleValidationException(ValidationException e) {
        logger.error("参数验证失败", e);
        //return new RespData(HttpStatus.BAD_REQUEST.value(),"参数验证失败:"+e.getMessage());
        return reFail("参数验证失败:"+e.getMessage());
    }

    /**
     * 404 - Not Found
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public RespData noHandlerFoundException(NoHandlerFoundException e) {
        logger.error("404 = "+e.getMessage());
        //return new RespData(HttpStatus.NOT_FOUND.value(),e.getMessage());
        return reFail("404 = "+e.getMessage());
    }


    /**
     * 405 - Method Not Allowed
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public RespData handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        logger.error("不支持当前请求方法", e);
        //return new RespData(HttpStatus.METHOD_NOT_ALLOWED.value(),"不支持当前请求方法:"+e.getMessage());
        return reFail("不支持当前请求方法:"+e.getMessage());
    }

    /**
     * 415 - Unsupported Media Type
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public RespData handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
        logger.error("不支持当前媒体类型", e);
        //return new RespData(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(),"不支持当前媒体类型:"+e.getMessage());
        return reFail("不支持当前媒体类型:"+e.getMessage());
    }
    /**
     * 业务层需要自己声明异常的情况
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(ServiceException.class)
    public RespData handleServiceException(ServiceException e) {
        logger.error("业务逻辑异常", e);
        //return new RespData(HttpStatus.INTERNAL_SERVER_ERROR.value(),"业务逻辑异常:"+e.getMessage());
        return reFail("业务逻辑异常:"+e.getMessage());
    }
    /**
     * 操作数据或库出现异常
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(DataDoException.class)
    public RespData handleException(DataDoException e) {
        logger.error("操作数据或库出现异常:", e);
        //return new RespData(HttpStatus.INTERNAL_SERVER_ERROR.value(),"操作数据或库出现异常:"+e.getMessage());
        return reFail("操作数据或库出现异常:"+e.getMessage());
    }

    /**
     * 500 - Internal Server Error
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public String handleException(Exception e) {
        logger.error("500异常", e);
        return "500异常：" + e.getMessage();
    }

    /**
     * 获取其它异常。包括500
     * @param e
     * @return
     * @throws Exception
     */
    /*@ExceptionHandler(value = Exception.class)
    public RespData defaultErrorHandler(Exception e){
       logger.error("其他异常(包含500)", e);
       return new RespData(HttpStatus.INTERNAL_SERVER_ERROR.value(),"异常:"+e.getMessage());
    }*/

}
